/**
 * 
 */
package org.gtiles.components.login.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtiles.components.login.web.DefaultLoginJsonRenderImpl;
import org.gtiles.components.login.web.ILoginJsonRender;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.util.StringUtils;

/**
 * 通过URL中的“login_ct”参数进行判断。
 * <code>if (login_ct != null && login_ct.equals("ajax"))</code>
 * ,仅返回登录成功的json，反之按spring security原有逻辑跳转相关的URL请求<br>
 * 1、可以通过修改系统参数中的“plugins_login_jsonRenderBean”来扩展“login_ct”请求返回的json内容；<br>
 * 2、可以通过修改系统参数中的“plugins_login_logoutSuccessUrl”来配置登出成功后跳转的路径；<br>
 * 
 * @author GuoR
 * @createDate 2016年3月18日
 */
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

	@Override
	protected void handle(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		
		// 获取登录方式参数
		String clientType = request.getParameter("login_ct");
		String targetUrl = determineTargetUrl(request, response);
//		if (response.isCommitted()) {
//			logger.debug("Response has already been committed. Unable to redirect to "
//					+ targetUrl);
//			return;
//		}
//		String jsonRenderBean = (String) ConfigHolder.getConfigValue(
//				ComponentPlugin.PLUGIN_CODE, "plugins_login_jsonRenderBean");
//		Assert.notNull(jsonRenderBean, "jsonRenderBean cannot be null");
		// 仅对AJAX的请求，返回登出成功的json信息
		if (!StringUtils.isEmpty(clientType) && clientType.equals("ajax")) {
			try {
				ILoginJsonRender jsonRender = new DefaultLoginJsonRenderImpl();
				jsonRender.logoutSuccess(request, response);
			} catch (Exception e) {
				throw new RuntimeException("登录json格式数据处理类实例化失败，请检查相关参数配置及接口实现是否正确。",e);
			}
		} else {
			getRedirectStrategy().sendRedirect(request, response, targetUrl);
		}
	}
	
	@Override
	protected String determineTargetUrl(HttpServletRequest request,
			HttpServletResponse response) {
//		initParam();
		return super.determineTargetUrl(request, response);
	}

	@Override
	public void onLogoutSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		handle(request, response, authentication);
	}

//	protected void initParam() {
//		String defaultTargetUrl = (String) ConfigHolder
//				.getConfigValue(
//						ComponentPlugin.PLUGIN_CODE,
//						"plugins_login_logoutSuccessUrl");
//		if (!StringUtils.isEmpty(defaultTargetUrl)) {
//			super.setDefaultTargetUrl(defaultTargetUrl);
//		}
//	}
}
